<script setup lang="ts">
import { getSubjectListByUserId,  removeSubject } from '@/api/subject';
import { Subject } from '@/api/subject/type';
import MySubject from '@/components/icons/subject/MySubject.vue';
import { router } from '@/router';
import { onMounted, ref } from 'vue';
import { showToast, showDialog, Empty as VanEmpty, Skeleton as VanSkeleton} from 'vant';
import { useUserStore } from '@/store/user';

const subjectList = ref([] as Subject[]);
const loading = ref(false);
const refreshing = ref(false);
const isManageMode = ref(false); // 管理模式状态

const toCreate = () => {
    router.push({name: 'SubjectCreate'});
}

const fetchSubjectList = async () => {
    try {
        loading.value = true;
        const userStore = useUserStore();
        const res = await getSubjectListByUserId(userStore.getId);
        subjectList.value = res.data;
    } catch (error) {
        showToast('获取题目集失败');
    } finally {
        loading.value = false;
        refreshing.value = false;
    }
};

onMounted(() => {
    fetchSubjectList();
});

const toHome = (id: string) => {
    // 管理模式下不跳转
    if (isManageMode.value) return;
    
    router.push({
        name: "SubjectHome",
        query: {
            "id": id
        }
    });
}

const onRefresh = () => {
    refreshing.value = true;
    fetchSubjectList();
}

const toggleManageMode = () => {
    isManageMode.value = !isManageMode.value;
}

const confirmDelete = (event: Event, id: string, name: string) => {
    // 阻止冒泡，避免触发toHome
    event.stopPropagation();
    
    showDialog({
        title: '删除题目集',
        message: `确定要删除"${name}"题目集吗？`,
        showCancelButton: true,
        confirmButtonText: '删除',
        confirmButtonColor: '#ee0a24',
    }).then(() => {
        deleteSubject(id);
    }).catch(() => {
        // 用户取消删除
    });
}

const deleteSubject = async (id: string) => {
    try {
        await removeSubject(id);
        showToast('删除成功');
        // 刷新列表
        fetchSubjectList();
    } catch (error) {
        showToast('删除失败');
    }
}
</script>

<template>
  <div class="mySubjectList">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="pull-refresh">
      <div class="header-row">
        <div class="my">
          <MySubject></MySubject>
          <div class="text">
            <p>我的题目集</p>
          </div>
        </div>
        <div class="actions">
          <van-button 
              :icon="isManageMode ? 'success' : 'setting-o'" 
              :type="isManageMode ? 'success' : 'default'"
              size="small" 
              round 
              plain 
              @click="toggleManageMode">
              {{ isManageMode ? '完成' : '管理' }}
          </van-button>
          <van-button 
              class="create-btn" 
              icon="plus" 
              type="primary" 
              round 
              size="small" 
              @click="toCreate">
              创建题目集
          </van-button>
        </div>
      </div>
      
      <van-empty v-if="!loading && subjectList.length === 0" description="暂无题目集" />
      
      <div v-else class="list-container">
        <van-skeleton title :row="3" :loading="loading" v-for="i in 3" :key="`skeleton-${i}`" v-if="loading"></van-skeleton>
        <div v-else class="list">
          <div 
              v-for="(item, index) in subjectList" 
              class="item" 
              :class="{ 'manage-mode': isManageMode }"
              :key="index" 
              @click="toHome(item.id)">
            <div class="avatar">
              <van-image :src="item.avatar" width="60px" height="60px" radius="4px" fit="cover"></van-image>
            </div>
            <div class="info">
              <div class="name">{{ item.name }}</div>
            </div>
            <div v-if="isManageMode" class="delete-icon">
              <van-icon name="delete-o" color="#ee0a24" size="20" @click.stop="(e) => confirmDelete(e, item.id, item.name)" />
            </div>
          </div>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<style lang="scss" scoped>
.mySubjectList {
  width: 100%;
  height: 100%;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 确保内容不会溢出 */
}

/* 使用pull-refresh类添加样式 */
.pull-refresh {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden; /* 控制外部溢出 */
}

.header-row {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f5f5f5;
  flex-shrink: 0; /* 防止头部被压缩 */
  
  .my {
    display: flex;
    align-items: center;
    
    .text {
      margin-left: 12px;
      
      p {
        font-size: 18px;
        font-weight: 500;
        margin: 0;
      }
    }
  }
  
  .actions {
    display: flex;
    align-items: center;
    
    .create-btn {
      margin-left: 8px;
    }
  }
}

.list-container {
  flex: 1;
  overflow-y: auto; /* 仅允许垂直滚动 */
  -webkit-overflow-scrolling: touch;
  height: 0; /* 关键：设置高度为0，让flex-grow撑开 */
  
  .list {
    .item {
      display: flex;
      padding: 12px 16px;
      align-items: center;
      border-bottom: 1px solid #f5f5f5;
      position: relative;
      transition: all 0.2s;
      
      &.manage-mode {
        background-color: #fafafa;
        padding-right: 50px;
      }
      
      &:active:not(.manage-mode) {
        background-color: #f9f9f9;
      }
      
      .avatar {
        width: 60px;
        height: 60px;
        flex-shrink: 0;
        border-radius: 4px;
        overflow: hidden;
      }
      
      .info {
        flex: 1;
        margin-left: 16px;
        display: flex;
        flex-direction: column;
        
        .name {
          font-size: 16px;
          font-weight: 500;
          word-break: break-word;
          line-height: 1.4;
        }
      }
      
      .delete-icon {
        position: absolute;
        right: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 30px;
        height: 30px;
      }
    }
  }
}

:deep(.van-pull-refresh) {
  overflow: visible;
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%; /* 确保占满容器高度 */
}

:deep(.van-pull-refresh__track) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 100%; /* 确保内容占满容器 */
}

/* 确保van-empty正确显示在中间 */
:deep(.van-empty) {
  padding: 32px 0;
}
</style>